package com.vader.netty.chat;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;

/**
 * @author kaivader
 */
public class NettyServerHandler extends SimpleChannelInboundHandler<String> {

    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channels.writeAndFlush(simpleDateFormat.format(System.currentTimeMillis()) +"[client]:"+ channel.remoteAddress() + "  join chat\n");
        channels.add(channel);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(simpleDateFormat.format(System.currentTimeMillis()) +ctx.channel().remoteAddress() + "online");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(simpleDateFormat.format(System.currentTimeMillis()) +ctx.channel().remoteAddress() + "unLine");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channels.writeAndFlush(simpleDateFormat.format(System.currentTimeMillis()) +"[client]:" + channel.remoteAddress() + "  leave chat\n");
        channels.remove(channel);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        Channel channel = channelHandlerContext.channel();
        channels.forEach(otherChannel -> {
            if (otherChannel != channel) {
                otherChannel.writeAndFlush(simpleDateFormat.format(System.currentTimeMillis()) +"[user]" + channel.remoteAddress() + "send message" + s);
            } else {
                otherChannel.writeAndFlush(simpleDateFormat.format(System.currentTimeMillis()) +"[me]" + channel.remoteAddress() + "send message" + s);
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.channel();
    }
}
